#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : SQLSession.py
# @Author: Xuhao
# @Date  : 2018/3/12
# @Desc  : 


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base



# 初始化数据库连接: MySqlXuhao@47.94.105.135:3306
engine = create_engine('mysql+pymysql://root:MySqlXuhao@127.0.0.1:3306/HiXiaoShuo?charset=utf8',
                       encoding='utf-8',
                       echo=False,
                       pool_size=100,
                       pool_recycle=3600
                       )

#生成 ORM 基类
Base = declarative_base()
# Base.metadata.create_all(engine)
# Session_class = sessionmaker(bind=engine)  # 实例和engine绑定
#
# session = Session_class()  # 生成session实例，相当于游标

class DataBaseConnector():
    engin = None
    Session = None

    def __init__(self):
        self.connect()


    def connect(self):

        if self.engin is None:
            self.engin = create_engine('mysql+pymysql://root:MySqlXuhao@47.94.105.135:3306/BaiYue?charset=utf8',
                       encoding='utf-8',
                       echo=False,
                       pool_size=100,
                       pool_recycle=3600
                       )
        if self.Session is None:
            self.Session = scoped_session(sessionmaker(bind=self.engin, expire_on_commit=False))


    def get_session(self):
        self.connect()
        return  self.Session()

    def close(self):
        self.Session.remove()

from app.common.pyDbRowFactory import DbRowFactory

import json
from app.common.Tool import Tool
#定义小说信息表
class NoverInfo():
    id = 0
    book_id = ""
    book_url = ""
    book_domain = ""
    book_enable = 0

    # def __init__(self, id, book_id, book_url, book_domain, book_enable):
    #     self.id = id
    #     self.book

if __name__ == "__main__":


    connect = DataBaseConnector()

    session = connect.get_session()

    sql = "select * from book_source WHERE book_domain='suimeng' and book_enable=1"

    list = session.execute(sql)

    # factory = DbRowFactory.fromSqlAlchemyResultProxy(resultProxy=list,
    #                                                  rowClassFullName="app.Sql.SQLSession.NoverInfo")

    # bb =factory.fetchOneRowObject()
    i =  1
    count = 29683
    for book in list:

        book_id =  book["book_id"]
        domain = book["book_domain"]

        # 修改数据库
        sql = "update book_source set book_enable=%d WHERE book_id='%s' and book_domain='%s'" % (0, book_id, domain)

        #print(sql)
        session.execute(sql)
        session.commit()
        print("一共%d条数据 剩余%d条" % (count,count - i) )
        i+=1




